package view;

import java.io.*;
import java.util.*;

public class OrderView {
    private static List<String> orders = new ArrayList<>();
    private static List<String> products = new ArrayList<>();
    private static Map<String, Double> userPoints = new HashMap<>();
    private static String currentUser = "defaultUser";

    public OrderView() {
        // 初始化用户积分
        userPoints.put(currentUser, 0.0);
    }

    public static void setCurrentUser(String user) {
        currentUser = user;
    }

    public static void updateProductList(List<String> updatedProducts) {
        products = new ArrayList<>(updatedProducts);
    }

    public static void loadProductsFromFile(String filePath) {
        products.clear(); // 清空现有商品列表
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                products.add(line);
            }
        } catch (IOException e) {
            System.out.println("无法读取商品数据: " + e.getMessage());
        }
    }

    public static void loadPointsFromFile(String filePath) {
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(" ");
                userPoints.put(parts[0], Double.parseDouble(parts[1]));
            }
        } catch (IOException e) {
            System.out.println("无法读取积分数据: " + e.getMessage());
        }
    }

    public static void savePointsToFile(String filePath) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            for (Map.Entry<String, Double> entry : userPoints.entrySet()) {
                writer.write(entry.getKey() + " " + entry.getValue());
                writer.newLine();
            }
        } catch (IOException e) {
            System.out.println("无法保存积分数据: " + e.getMessage());
        }
    }

    public static void displayMenu() {
        // 初始化商品列表
        loadProductsFromFile("C:\\Users\\lenovo\\IdeaProjects\\wang-jingbos-father真的最后了\\项目源码\\src\\products.txt");

        while (true) {
            System.out.println("1. 下单");
            System.out.println("2. 支付");
            System.out.println("3. 退款");
            System.out.println("4. 查看积分");
            System.out.println("5. 退出");
            System.out.print("Choose an option: ");

            int option = new Scanner(System.in).nextInt();
            switch (option) {
                case 1:
                    placeOrder();
                    break;
                case 2:
                    payOrder();
                    break;
                case 3:
                    refundOrder();
                    break;
                case 4:
                    viewPoints();
                    break;
                case 5:
                    savePointsToFile("C:\\Users\\lenovo\\IdeaProjects\\wang-jingbos-father真的最后了\\项目源码\\src\\points.txt");
                    return;
                default:
                    System.out.println("Invalid option. Please try again.");
            }
        }
    }

    private static void placeOrder() {
        if (products.isEmpty()) {
            System.out.println("没有商品可供选择.");
            return;
        }

        System.out.println("下单:");
        System.out.println("可选商品:");
        for (int i = 0; i < products.size(); i++) {
            System.out.println((i + 1) + ". " + products.get(i));
        }

        System.out.print("选择商品编号: ");
        int productIndex = new Scanner(System.in).nextInt() - 1;
        if (productIndex >= 0 && productIndex < products.size()) {
            String productInfo = products.get(productIndex);
            String[] productParts = productInfo.split(" ");
            String productName = productParts[0];
            double productPrice = Double.parseDouble(productParts[1]); // 解析浮点数价格

            System.out.print("输入购买数量: ");
            int quantity = new Scanner(System.in).nextInt();

            double totalPrice = productPrice * quantity;
            String order = String.format("%s %.2f %d", productName, productPrice, quantity);
            orders.add(order);

            System.out.println("订单已添加: " + order);
        } else {
            System.out.println("无效的商品编号.");
        }
    }

    private static void payOrder() {
        if (orders.isEmpty()) {
            System.out.println("没有未支付的订单.");
            return;
        }

        System.out.println("支付订单:");
        double totalAmount = 0.0;
        for (String order : orders) {
            System.out.println("订单: " + order);
            String[] orderParts = order.split(" ");
            double price = Double.parseDouble(orderParts[1]);
            int quantity = Integer.parseInt(orderParts[2]);
            totalAmount += price * quantity;
        }

        orders.clear();
        double currentPoints = userPoints.getOrDefault(currentUser, 0.0);
        userPoints.put(currentUser, currentPoints + totalAmount);

        System.out.println("所有订单已支付. 你现在有 " + (currentPoints + totalAmount) + " 积分.（支付完不可退款了哦，开弓没有回头箭，人生没有回头路）");
    }

    private static void refundOrder() {
        if (orders.isEmpty()) {
            System.out.println("没有订单可以退款.");
            return;
        }

        System.out.println("退款订单:");
        for (int i = 0; i < orders.size(); i++) {
            System.out.println((i + 1) + ". " + orders.get(i));
        }

        System.out.print("选择要退款的订单编号: ");
        int orderIndex = new Scanner(System.in).nextInt() - 1;
        if (orderIndex >= 0 && orderIndex < orders.size()) {
            String order = orders.remove(orderIndex);
            String[] orderParts = order.split(" ");
            double price = Double.parseDouble(orderParts[1]);
            int quantity = Integer.parseInt(orderParts[2]);
            double amount = price * quantity;

            // 减少积分
            double currentPoints = userPoints.getOrDefault(currentUser, 0.0);
            userPoints.put(currentUser, currentPoints - amount);
            System.out.println("订单已退款: " + order + ". 你现在有 " + (currentPoints - amount) + " 积分.");
        } else {
            System.out.println("无效的订单编号.");
        }
    }

    private static void viewPoints() {
        double currentPoints = userPoints.getOrDefault(currentUser, 0.0);
        System.out.println("你现在有 " + currentPoints + " 积分.");
    }
}
